package com.stars.easyms.rest.handler;

import com.stars.easyms.rest.bean.EasyMsRestContext;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import java.io.IOException;
import java.util.List;

/**
 * <p>className: EasyMsRequestResponseBodyMethodProcessor</p>
 * <p>description: EasyMsRequestResponseBodyMethodProcessor</p>
 *
 * @author guoguifang
 * @version 1.7.1
 * @date 2020/12/14 4:39 下午
 */
public class EasyMsRequestResponseBodyMethodProcessor extends RequestResponseBodyMethodProcessor {

    public EasyMsRequestResponseBodyMethodProcessor(List<HttpMessageConverter<?>> converters,
                                                    @Nullable ContentNegotiationManager manager,
                                                    @Nullable List<Object> requestResponseBodyAdvice) {
        super(converters, manager, requestResponseBodyAdvice);
    }

    @Override
    public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest)
            throws IOException, HttpMediaTypeNotAcceptableException, HttpMessageNotWritableException {

        // 获取rest上下文并封装响应值，如果为空则跳过
        EasyMsRestContext easyMsRestContext = EasyMsRestSynchronizationManager.getEasyMsRestContext();
        if (easyMsRestContext != null) {
            Object responseEntity = easyMsRestContext.getResponseEntity();
            if (responseEntity == null) {
                returnValue = ResponseEntityHelper.getResponseEntity(easyMsRestContext);
            } else {
                returnValue = responseEntity;
            }
        }
        super.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    }

}
